﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;
using System.Windows.Media.Imaging;
using System.Threading;

namespace SilverlightPlayground.LightBox
{
    public partial class MainPage : UserControl
    {
        private int _loading = 0;

        /// <summary>
        /// Initializes a new instance of the <see cref="MainPage"/> class.
        /// </summary>
        public MainPage()
        {
            InitializeComponent();

            this.KeyUp += new KeyEventHandler(Page_KeyUp);
            this.MouseMove += new MouseEventHandler(MainPage_MouseMove);
            this.image.ImageOpened += new EventHandler<RoutedEventArgs>(image_ImageOpened);
            this.PrevButton.Click += new RoutedEventHandler(PrevButton_Click);
            this.NextButton.Click += new RoutedEventHandler(NextButton_Click);

            SlideShowCoordinator.Current.Initialize += new EventHandler(SlideShowCoordinator_Initialize);
            SlideShowCoordinator.Current.ImageChanged += new EventHandler(SlideShowCoordinator_ImageChanged);

            Timer timer = new Timer(new TimerCallback(Timer_tick), null, 0, 1000);
        }

        void Timer_tick(object state)
        {
            int count = Interlocked.Decrement(ref tickCount);

            if (count == 0)
                Deployment.Current.Dispatcher.BeginInvoke(
                    () => VisualStateManager.GoToState(this, "Normal", true));
        }

        private int tickCount;

        void MainPage_MouseMove(object sender, MouseEventArgs e)
        {
            if (!waitStar.IsWaiting && SlideShowCoordinator.Current.Images.Count > 1)
            {
                Interlocked.Exchange(ref tickCount, 3);
                VisualStateManager.GoToState(this, "Show", true);
            }
        }

        /// <summary>
        /// Handles the Initialize event of the Current control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SlideShowCoordinator_Initialize(object sender, EventArgs e)
        {
            VisualStateManager.GoToState(this, "Normal", false);
            HtmlBridge.Focus();
            this.ExecuteStoryboard(init, () => this.DataContext = SlideShowCoordinator.Current);
        }

        /// <summary>
        /// Handles the ImageChanged event of the Current control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void SlideShowCoordinator_ImageChanged(object sender, EventArgs e)
        {
            Interlocked.Exchange(ref _loading, 1);

            ThreadPool.QueueUserWorkItem(
                o =>
                {
                    Thread.Sleep(1000);

                    if (Interlocked.Exchange(ref _loading, 0) == 1)
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                            {
                                waitStar.IsWaiting = true;
                                VisualStateManager.GoToState(this, "Normal", true);
                            });
                });
        }

        /// <summary>
        /// Handles the KeyUp event of the LayoutRoot control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs"/> instance containing the event data.</param>
        void Page_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Right)
                this.ExecuteStoryboard(exit, () => SlideShowCoordinator.Current.MoveNext());
            if (e.Key == Key.Escape)
                HtmlBridge.Hide();
            if (e.Key == Key.Left)
                this.ExecuteStoryboard(exit, () => SlideShowCoordinator.Current.MovePrevious());
        }

        /// <summary>
        /// Handles the ImageOpened event of the image control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        void image_ImageOpened(object sender, RoutedEventArgs e)
        {
            Interlocked.Exchange(ref _loading, 0);

            BitmapImage bmap = image.Source as BitmapImage;

            if (image != null)
            {
                image.MaxWidth = bmap.PixelWidth;
                image.MaxHeight = bmap.PixelHeight;
                image.Stretch = Stretch.Uniform;
                waitStar.IsWaiting = false;
                this.ExecuteStoryboard(enter, () => { });
            }

            image.Opacity = 1.0;
        }

        /// <summary>
        /// Handles the MouseLeftButtonUp event of the image control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
        private void image_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.ExecuteStoryboard(unload, () => HtmlBridge.Hide());
        }

        /// <summary>
        /// Handles the Click event of the NextButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void NextButton_Click(object sender, RoutedEventArgs e)
        {
            Interlocked.Exchange(ref tickCount, 5);
            this.ExecuteStoryboard(exit, () => SlideShowCoordinator.Current.MoveNext());
        }

        /// <summary>
        /// Handles the Click event of the PrevButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
        private void PrevButton_Click(object sender, RoutedEventArgs e)
        {
            Interlocked.Exchange(ref tickCount, 5);
            this.ExecuteStoryboard(exit, () => SlideShowCoordinator.Current.MovePrevious());
        }

        /// <summary>
        /// Plays the specified sb.
        /// </summary>
        /// <param name="sb">The sb.</param>
        /// <param name="completed">The completed.</param>
        private void ExecuteStoryboard(Storyboard sb, Action completed)
        {
            EventHandler handler = null;

            handler = (s, e) =>
            {
                sb.Completed -= handler;
                completed();
            };

            sb.Completed += handler;
            sb.Begin();
        }
    }
}